<template>
  <!-- 外层添加div包裹，设置class用于控制全屏问题 -->
  <div class="design-order-container">
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="订单编号">
                <a-input placeholder="请输入订单编号" v-model="queryParam.orderNo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="客户名称">
                <a-input placeholder="请输入客户名称" v-model="queryParam.customerName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="客户省份">
                <a-input placeholder="请输入客户省份" v-model="queryParam.customerProvince"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="客户城市">
                <a-input placeholder="请输入客户城市" v-model="queryParam.customerCity"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="工程名称">
                <a-input placeholder="请输入工程名称" v-model="queryParam.projectName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="工程省份">
                <a-input placeholder="请输入工程省份" v-model="queryParam.projectProvince"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="工程城市">
                <a-input placeholder="请输入工程城市" v-model="queryParam.projectCity"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="订单状态">
                <j-dict-select-tag
                  v-model="queryParam.status"
                  placeholder="请选择订单状态"
                  dictCode="order_status"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                <a-button style="margin-left: 8px" type="primary" icon="reload" @click="refreshPage">刷新</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 表格区域 -->
      <div>
        <div class="table-operator" style="margin-bottom: 16px">
          <!-- 合单优化上传按钮 -->
          <a-button
            type="primary"
            icon="cloud-upload"
            :disabled="selectedRowKeys.length === 0"
            @click="handleBatchUploadOptimization"
            style="margin-right: 8px"
          >
            合单优化上传 ({{ selectedRowKeys.length }})
          </a-button>
        </div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :scroll="{ x: true }"
          :rowSelection="rowSelection"
          @change="handleTableChange"
        >
          <!-- 订单状态 -->
          <span slot="statusSlot" slot-scope="text">
            <j-dict-tag :value="text" dictCode="order_status" />
          </span>

          <!-- 客户地址 -->
          <template slot="customerAddressSlot" slot-scope="text, record">
            <span>{{
              [record.customerProvince, record.customerCity, record.customerDistrict].filter(Boolean).join(' ')
            }}</span>
          </template>

          <!-- 工程地址 -->
          <template slot="projectAddressSlot" slot-scope="text, record">
            <span>{{
              [record.projectProvince, record.projectCity, record.projectDistrict].filter(Boolean).join(' ')
            }}</span>
          </template>

          <!-- 优化软件类型 -->
          <template slot="optimizeSoftTypeSlot" slot-scope="text">
            <span>{{ text == 0 ? '长风优化软件' : '新格尔优化软件' }}</span>
          </template>

          <!-- 操作按钮区域 -->
          <span slot="action" slot-scope="text, record">
            <a-button type="link" size="small" @click="handleDetail(record)"> <a-icon type="eye" /> 明细 </a-button>

            <!-- 待上传状态 -->
            <template v-if="record.status == '1'">
              <a-button
                type="link"
                size="small"
                @click="handleUploadSummary(record)"
                v-if="record.optimizationSoftwareType == 1 && record.windowDoorType != 1"
              >
                <a-icon type="upload" /> 上传汇总
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="handleUploadOptimization(record)"
                v-if="
                  record.optimizationSoftwareType == 0 ||
                  (record.optimizationSoftwareType == 1 && record.windowDoorType == 1)
                "
              >
                <a-icon type="cloud-upload" /> 上传优化
              </a-button>
            </template>

            <!-- 已上传汇总单状态 -->
            <template v-else-if="record.status == '2'">
              <a-button type="link" size="small" @click="handleCancelUpload(record)">
                <a-icon type="rollback" /> 取消
              </a-button>
              <a-button type="link" size="small" @click="handleUploadOptimization(record)">
                <a-icon type="cloud-upload" /> 上传优化
              </a-button>
            </template>

            <!-- 已上传优化单状态 -->
            <template v-else-if="record.status == '3'">
              <a-button type="link" size="small" @click="handleCancelUpload(record)">
                <a-icon type="rollback" /> 取消
              </a-button>
              <a-button type="link" size="small" @click="handleSubmitForReview(record)">
                <a-icon type="check-circle" /> 提交审核
              </a-button>
            </template>

            <!-- 已驳回状态 -->
            <template v-else-if="record.status == '9'">
              <a-button type="link" size="small" @click="handleReupload(record)">
                <a-icon type="reload" /> 重新上传
              </a-button>
            </template>
          </span>
        </a-table>
      </div>

      <!-- 上传汇总单弹窗 -->
      <upload-summary-modal
        ref="uploadSummaryModal"
        :orderId="summaryOrderId"
        :orderNo="summaryOrderNo"
        @upload-success="handleSummaryUploadSuccess"
      />

      <!-- 上传优化单弹窗 -->
      <a-modal
        :title="'上传优化单 - ' + confirmOrderInfo.orderNo"
        :visible="uploadOptimizationVisible"
        :confirmLoading="confirmLoading"
        @ok="handleUploadOptimizationOk"
        @cancel="handleUploadOptimizationCancel"
      >
        <a-alert message="请上传优化单文件，支持XML和Excel格式" type="info" show-icon style="margin-bottom: 16px" />
        <a-upload name="file" :multiple="false" :beforeUpload="beforeUploadOptimization" :fileList="fileList">
          <a-button> <a-icon type="upload" /> 选择文件 </a-button>
          <div class="ant-upload-hint" style="margin-top: 10px">请选择优化单文件（支持XML和Excel格式）</div>
        </a-upload>
      </a-modal>

      <!-- 订单详情弹窗 -->
      <design-order-detail ref="detailModal"></design-order-detail>

      <!-- 提交审核 型材清单、配件清单模态框 -->
      <submit-review-modal
        ref="submitReviewModal"
        :orderId="confirmOrderInfo.id || ''"
        @submit-success="loadData"
      ></submit-review-modal>

      <!-- 合单优化上传弹窗 -->
      <a-modal
        title="合单优化上传"
        :visible="batchUploadVisible"
        :confirmLoading="confirmLoading"
        @ok="handleBatchUploadOk"
        @cancel="handleBatchUploadCancel"
        width="600px"
      >
        <div style="margin-bottom: 16px">
          <a-alert
            message="已选择订单"
            :description="`共选择了 ${selectedRowKeys.length} 个订单进行合单优化上传`"
            type="info"
            show-icon
          />
        </div>
        <div style="margin-bottom: 16px; max-height: 200px; overflow-y: auto">
          <a-table
            :columns="selectedOrderColumns"
            :dataSource="selectedOrders"
            :pagination="false"
            size="small"
            rowKey="id"
          />
        </div>
        <a-alert message="请上传优化单文件，支持XML和Excel格式" type="info" show-icon style="margin-bottom: 16px" />
        <a-upload name="file" :multiple="false" :beforeUpload="beforeUploadBatchOptimization" :fileList="batchFileList">
          <a-button> <a-icon type="upload" /> 选择文件 </a-button>
          <div class="ant-upload-hint" style="margin-top: 10px">请选择优化单文件（支持XML和Excel格式）</div>
        </a-upload>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getApprovedOrderList, uploadSummaryFile, cancelUploadedFiles } from '@/api/oms/productOrder'
import DesignOrderDetail from './modules/DesignOrderDetail'
import UploadSummaryModal from './modules/UploadSummaryModal'
import { mapGetters } from 'vuex'
import { getAction, postAction, uploadAction } from '@/api/manage'
import { message } from 'ant-design-vue'
import JDictTag from '@/components/dict/JDictTag'
import {
  validateSummaryFile,
  processSummaryFileResult,
  uploadOptimization,
  getOrderMaterialsAndAccessories,
} from '@/api/oms/designFile'
import SubmitReviewModal from './modules/SubmitReviewModal'

export default {
  name: 'DesignOrderList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    DesignOrderDetail,
    UploadSummaryModal,
    JDictTag,
    SubmitReviewModal,
  },
  // 添加keep-alive缓存控制
  activated() {
    // 当组件被激活时，确保数据是最新的
    console.log('DesignOrderList组件被激活')
    this.loadData()
  },
  // 添加页面缓存控制
  beforeRouteLeave(to, from, next) {
    // 在路由离开前执行一些操作
    console.log('DesignOrderList路由即将离开')
    next()
  },
  computed: {
    ...mapGetters(['userInfo']),
    // 行选择配置
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        getCheckboxProps: (record) => ({
          disabled: record.status !== '2' && record.status !== '1', // 只允许选择状态为1或2的订单
        }),
      }
    },
    // 选中的订单数据
    selectedOrders() {
      return this.dataSource.filter((item) => this.selectedRowKeys.includes(item.id))
    },
  },
  data() {
    return {
      description: '设计管理-订单列表',
      // 查询条件
      queryParam: {
        orderNo: '',
        customerName: '',
        customerProvince: '',
        customerCity: '',
        customerDistrict: '',
        projectName: '',
        projectProvince: '',
        projectCity: '',
        projectDistrict: '',
        status: null,
      },
      // 表格列配置
      columns: [
        {
          title: '订单编号',
          align: 'center',
          dataIndex: 'orderNo',
          width: 150,
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customerName',
        },
        {
          title: '客户地址',
          align: 'center',
          dataIndex: 'customerProvince',
          width: 180,
          scopedSlots: { customRender: 'customerAddressSlot' },
        },
        {
          title: '工程名称',
          align: 'center',
          dataIndex: 'projectName',
        },
        {
          title: '工程地址',
          align: 'center',
          dataIndex: 'projectProvince',
          width: 180,
          scopedSlots: { customRender: 'projectAddressSlot' },
        },
        {
          title: '订单日期',
          align: 'center',
          dataIndex: 'orderDate',
          width: 120,
        },
        {
          title: '交付日期',
          align: 'center',
          dataIndex: 'deliveryDate',
          width: 120,
        },
        {
          title: '优化软件类型',
          align: 'center',
          dataIndex: 'optimizationSoftwareType',
          width: 100,
          scopedSlots: { customRender: 'optimizeSoftTypeSlot' },
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 220,
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 上传汇总单
      uploadSummaryVisible: false,
      // 上传优化单
      uploadOptimizationVisible: false,
      // 确认上传按钮loading
      confirmLoading: false,
      // 当前操作的订单信息
      confirmOrderInfo: {},
      // 上传的文件列表
      fileList: [],
      // 上传的文件
      uploadFile: null,
      url: {
        list: '/oms/productSalesOrder/approvedList',
        submitForReview: '/oms/productSalesOrder/submitForReview',
        updateOrderStatus: '/oms/productSalesOrder/updateOrderStatus',
      },
      // 汇总文件上传
      summaryOrderId: '',
      summaryOrderNo: '',
      summaryUploadResult: null,
      // 行选择相关
      selectedRowKeys: [],
      selectedRows: [],
      // 合单优化上传
      batchUploadVisible: false,
      batchFileList: [],
      batchUploadFile: null,
      selectedOrderColumns: [
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          width: 150,
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          width: 120,
        },
        {
          title: '工程名称',
          dataIndex: 'projectName',
        },
      ],
    }
  },
  created() {
    // 加载字典数据
    this.initDictConfig()

    // 页面加载时重置查询条件
    this.searchReset()
  },
  mounted() {
    // 修复全屏问题
    this.fixFullscreenIssue()
  },
  beforeDestroy() {
    // 组件销毁前清理
    console.log('DesignOrderList组件即将销毁')
  },
  methods: {
    // 加载数据
    loadData(arg) {
      if (arg == 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      getApprovedOrderList(Object.assign({}, this.queryParam, this.getQueryParams()))
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || []
            this.ipagination.total = res.result.total || 0
          } else {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
        .catch((error) => {
          console.error('加载数据失败:', error)
          this.$message.error('加载数据失败，请刷新页面重试')
          this.loading = false
        })
    },

    // 查看订单详情
    handleDetail(record) {
      if (!record || !record.id) {
        this.$message.warning('订单数据不完整，无法查看详情')
        return
      }
      this.$refs.detailModal.show(record.id)
    },

    // 上传汇总单
    handleUploadSummary(record) {
      this.summaryOrderId = record.id
      this.summaryOrderNo = record.orderNo
      // 使用UploadSummaryModal组件
      this.$refs.uploadSummaryModal.show()
    },

    // 汇总单上传成功的回调
    handleSummaryUploadSuccess() {
      // 刷新列表数据
      this.loadData()
      // 记录操作日志
      console.log('汇总单上传成功，订单ID:', this.summaryOrderId)
    },

    // 上传优化单
    handleUploadOptimization(record) {
      // 如果是长风软件，且状态是1（审核通过），自动处理为已上传汇总单
      if (record.optimizationSoftwareType == 0 && record.status == 1) {
        this.$message.info('长风软件用户无需上传汇总单，将直接上传优化单')
        // 可以在这里调用一个后端接口来更新状态，或者在上传优化单成功后自动更新状态
      }

      this.uploadOptimizationVisible = true
      this.confirmOrderInfo = record
      this.fileList = []
      this.uploadFile = null
    },

    // 优化单上传前的处理
    beforeUploadOptimization(file) {
      // 支持Excel和XML文件格式
      const isValidFile =
        file.type == 'application/vnd.ms-excel' ||
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.name.toLowerCase().endsWith('.xls') ||
        file.name.toLowerCase().endsWith('.xlsx') ||
        file.type == 'application/xml' ||
        file.type == 'text/xml' ||
        file.name.toLowerCase().endsWith('.xml')

      if (!isValidFile) {
        this.$message.error('请上传Excel格式或XML格式文件!')
      }

      // 检查文件大小
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!')
      }

      // 只有通过验证才添加到文件列表
      if (isValidFile && isLt10M) {
        this.fileList = [file]
        this.uploadFile = file
      }

      return false // 阻止自动上传，使用自定义上传
    },

    // 确认上传优化单
    handleUploadOptimizationOk() {
      if (!this.uploadFile) {
        this.$message.warning('请选择上传文件')
        return
      }

      // 构建表单数据
      const formData = new FormData()
      formData.append('orderId', this.confirmOrderInfo.id)
      formData.append('file', this.uploadFile)

      this.confirmLoading = true

      // 使用新的API接口
      uploadOptimization(formData)
        .then((res) => {
          if (res.success) {
            this.$message.success('优化单上传成功')
            this.uploadOptimizationVisible = false

            console.log('上传优化单成功，返回数据:', res.result)
            // 获取型材清单和配件清单
            this.loading = true
            getOrderMaterialsAndAccessories(this.confirmOrderInfo.id)
              .then((materialRes) => {
                if (materialRes.success) {
                  console.log('获取型材清单和配件清单成功，数据:', materialRes.result)
                  // 显示型材清单模态框
                  this.$nextTick(() => {
                    this.$refs.submitReviewModal.show(
                      materialRes.result.profileMaterials,
                      materialRes.result.accessories
                    )
                  })
                } else {
                  console.warn('未获取到型材清单和配件清单数据:', materialRes)
                  this.$message.warning('未获取到型材清单和配件清单数据')
                }
              })
              .catch((err) => {
                console.error('获取型材清单和配件清单出错', err)
                this.$message.error('获取型材清单和配件清单失败：' + (err.message || '未知错误'))
              })
              .finally(() => {
                this.loading = false
              })
          }
        })
        .catch((err) => {
          console.error('上传优化单出错', err)
          this.$message.error('上传优化单失败：' + (err.message || '未知错误'))
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // 取消上传优化单
    handleUploadOptimizationCancel() {
      this.uploadOptimizationVisible = false
      this.fileList = []
      this.uploadFile = null
    },

    // 新增方法修复全屏问题
    fixFullscreenIssue() {
      // 设置样式
      const style = document.createElement('style')
      style.type = 'text/css'
      style.innerHTML = `
        .design-order-container {
          height: auto !important;
          position: relative !important;
          overflow: visible !important;
        }
        .ant-card {
          max-height: none !important;
          overflow: visible !important;
          position: relative !important;
        }
        .ant-card-body {
          height: auto !important;
          max-height: none !important;
        }
        .fullscreen-enabled {
          position: relative !important;
          top: auto !important;
          left: auto !important;
          width: auto !important;
          height: auto !important;
          z-index: auto !important;
        }
      `
      document.head.appendChild(style)
    },
    refreshPage() {
      this.loadData(1)
    },
    // 提交审核
    handleSubmitForReview(record) {
      if (!record || !record.id) {
        this.$message.warning('订单数据不完整，无法提交审核')
        return
      }

      // 保存当前操作的订单信息
      this.confirmOrderInfo = record
      console.log('提交审核，当前订单ID:', record.id)

      // 显示提交审核模态框
      this.$nextTick(() => {
        this.$refs.submitReviewModal.show()
      })
    },

    // 重新上传（适用于已驳回的情况）
    handleReupload(record) {
      this.$confirm({
        title: '确认重新上传',
        content: `确定要重新上传订单 ${record.orderNo} 的文件吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.loading = true
          const params = {
            id: record.id,
            oldStatus: 9, // 已驳回状态
            newStatus: 1, // 审核通过-待上传状态
            changeReason: '设计人员重新上传',
          }
          postAction(this.url.updateOrderStatus, params)
            .then((res) => {
              if (res.success) {
                this.$message.success('状态已更新，请重新上传文件')
                this.loadData()
              } else {
                this.$message.error(res.message || '操作失败')
              }
            })
            .catch((err) => {
              console.error('重新上传操作出错', err)
              this.$message.error('操作失败')
            })
            .finally(() => {
              this.loading = false
            })
        },
      })
    },

    /**
     * 执行汇总文件上传
     */
    handleSummaryUpload({ file }) {
      this.confirmLoading = true
      const formData = new FormData()
      formData.append('file', file)
      formData.append('orderId', this.summaryOrderId)

      // 先验证文件
      validateSummaryFile(formData)
        .then((res) => {
          if (res.success) {
            // 验证成功，显示验证结果
            this.summaryUploadResult = res.result

            // 如果验证结果成功，自动进行上传
            if (this.summaryUploadResult.success) {
              // 上传文件并保存解析结果
              const uploadFormData = new FormData()
              uploadFormData.append('file', file)
              uploadFormData.append('orderId', this.summaryOrderId)
              uploadFormData.append('parseResult', JSON.stringify(this.summaryUploadResult))

              processSummaryFileResult(uploadFormData)
                .then((uploadRes) => {
                  if (uploadRes.success) {
                    this.$notification.success({
                      message: '上传成功',
                      description: `汇总单已成功上传，订单${this.summaryOrderNo}状态已更新为"已上传汇总单"`,
                      duration: 4,
                    })
                    this.uploadSummaryVisible = false
                    this.loadData() // 刷新列表
                  } else {
                    this.$message.error('保存解析结果失败: ' + (uploadRes.message || '未知错误'))
                  }
                })
                .catch((uploadErr) => {
                  this.$message.error('保存解析结果异常: ' + (uploadErr.message || uploadErr))
                })
            }
          } else {
            // 验证失败
            this.summaryUploadResult = {
              success: false,
              message: res.message || '文件验证失败',
            }
          }
        })
        .catch((err) => {
          // 处理验证错误
          this.summaryUploadResult = {
            success: false,
            message: '验证文件出错: ' + (err.message || err),
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // 汇总单上传前的处理
    beforeUploadSummary(file) {
      const isExcel =
        file.type == 'application/vnd.ms-excel' ||
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.name.toLowerCase().endsWith('.xls') ||
        file.name.toLowerCase().endsWith('.xlsx')
      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!')
      }
      return isExcel && isLt10M
    },

    // 确认上传汇总单
    handleUploadSummaryOk() {
      if (!this.uploadFile) {
        this.$message.warning('请选择上传文件')
        return
      }

      // 构建表单数据
      const formData = new FormData()
      formData.append('orderId', this.confirmOrderInfo.id)
      formData.append('file', this.uploadFile)

      this.confirmLoading = true

      // 调用上传接口
      uploadSummaryFile(formData)
        .then((res) => {
          if (res.success) {
            this.$message.success('汇总单上传成功')
            this.uploadSummaryVisible = false
            // 刷新数据
            this.loadData()
          } else {
            this.$message.error(res.message || '汇总单上传失败')
          }
          this.confirmLoading = false
        })
        .catch(() => {
          this.confirmLoading = false
        })
    },

    // 取消上传
    handleCancelUpload(record) {
      this.$confirm({
        title: '确认取消',
        content: `确定要取消订单 ${record.orderNo} 的文件上传吗？这将删除已上传的文件。`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.loading = true
          // 判断当前订单状态，确定取消的是汇总单还是优化单
          const status = parseInt(record.status)

          // 调用后端接口，使用API函数
          const params = {
            orderId: record.id,
            status: status,
          }

          cancelUploadedFiles(params)
            .then((res) => {
              if (res.success) {
                this.$message.success('取消上传成功')
                this.loadData()
              } else {
                this.$message.error(res.message || '取消上传失败')
              }
            })
            .catch((err) => {
              console.error('取消上传出错', err)
              this.$message.error('取消上传失败')
            })
            .finally(() => {
              this.loading = false
            })
        },
      })
    },

    // 行选择变化处理
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },

    // 合单优化上传
    handleBatchUploadOptimization() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请先选择要合单上传的订单')
        return
      }

      // 验证选中的订单是否都支持合单优化
      console.log('........................', this.selectedOrders)
      const invalidOrders = this.selectedOrders.filter((order) => order.status != '1' && order.status != '2')

      if (invalidOrders.length > 0) {
        this.$message.warning('只能选择状态为"审核通过-待上传"或"已上传汇总单-待上传优化单"的订单')
        return
      }

      this.batchUploadVisible = true
      this.batchFileList = []
      this.batchUploadFile = null
    },

    // 合单优化上传前的文件处理
    beforeUploadBatchOptimization(file) {
      // 支持Excel和XML文件格式
      const isValidFile =
        file.type === 'application/vnd.ms-excel' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.name.toLowerCase().endsWith('.xls') ||
        file.name.toLowerCase().endsWith('.xlsx') ||
        file.type === 'application/xml' ||
        file.type === 'text/xml' ||
        file.name.toLowerCase().endsWith('.xml')

      if (!isValidFile) {
        this.$message.error('请上传Excel格式或XML格式文件!')
        return false
      }

      // 检查文件大小
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!')
        return false
      }

      // 只有通过验证才添加到文件列表
      this.batchFileList = [file]
      this.batchUploadFile = file
      return false // 阻止自动上传，使用自定义上传
    },

    // 确认合单优化上传
    handleBatchUploadOk() {
      if (!this.batchUploadFile) {
        this.$message.warning('请选择上传文件')
        return
      }

      // 构建表单数据
      const formData = new FormData()
      // 将选中的订单ID拼接成字符串传递给后端
      formData.append('orderIds', this.selectedRowKeys.join(','))
      formData.append('file', this.batchUploadFile)

      this.confirmLoading = true

      // 调用合单优化上传接口
      uploadOptimization(formData)
        .then((res) => {
          if (res.success) {
            this.$message.success(`合单优化上传成功，共处理 ${this.selectedRowKeys.length} 个订单`)
            this.batchUploadVisible = false
            this.selectedRowKeys = []
            this.selectedRows = []
            // 刷新数据
            this.loadData()
          } else {
            this.$message.error(res.message || '合单优化上传失败')
          }
        })
        .catch((err) => {
          console.error('合单优化上传出错', err)
          this.$message.error('合单优化上传失败：' + (err.message || '未知错误'))
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // 取消合单优化上传
    handleBatchUploadCancel() {
      this.batchUploadVisible = false
      this.batchFileList = []
      this.batchUploadFile = null
    },
  },
}
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

/* 基础样式限制页面高度 */
.design-order-container {
  height: auto !important;
  position: relative !important;
  overflow: visible !important;
}

.ant-card {
  max-height: none !important;
  overflow: visible !important;
  position: relative !important;
}

/* 确保表格区域内容不超出 */
.table-page-search-wrapper {
  margin-bottom: 16px;
}

/* 防止表格撑满屏幕 */
.ant-table-wrapper {
  height: auto !important;
}
</style> 